package com.cans.lightning.business.lowcode.manager.form;

import com.cans.lightning.business.lowcode.manager.form.bean.AppFormBean;
import com.cans.lightning.business.lowcode.manager.form.cache.AppFormBeanCacheManager;
import com.cans.lightning.business.lowcode.manager.form.save.FormDesignSaveHandlerChainBuilder;
import com.cans.lightning.business.lowcode.manager.form.save.context.AppFormDesignSaveContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @author cans
 * @date 2023/11/28
 **/
@Component
public class AppFormBeanManager {

    private static final Logger logger = LoggerFactory.getLogger(AppFormBeanManager.class);

    @Resource
    private FormDesignSaveHandlerChainBuilder formDesignSaveHandlerChainBuilder;
    @Resource
    private AppFormBeanCacheManager appFormBeanCacheManager;

    public void saveToDb(AppFormBean appFormBean) throws ExecutionException {
        AppFormBean editFormBean = appFormBeanCacheManager.getEditFormBean(appFormBean.getId());
        formDesignSaveHandlerChainBuilder.getSaveHandlerChain().runSaveHandle(new AppFormDesignSaveContext<>(editFormBean));
    }

    public AppFormBean getFormBean(String id) {
        return appFormBeanCacheManager.get(id);
    }

    public AppFormBean formBeanDesign(String formId) throws ExecutionException {
        return appFormBeanCacheManager.createEditBean(formId);
    }

    public void mergeBaseInfo(AppFormBean appFormBean) throws ExecutionException {
        AppFormBean editFormBean = appFormBeanCacheManager.getEditFormBean(appFormBean.getId());
        appFormBean.setFieldIndex(editFormBean.getFieldIndex());
        appFormBeanCacheManager.updateEditFormBean(appFormBean);
    }

    public void removeEdit(String formId) {
        appFormBeanCacheManager.removeEditFormBean(formId);
    }

    public AppFormBean getEditBean(String formId) throws ExecutionException {
        return appFormBeanCacheManager.getEditFormBean(formId);
    }
}
